package com.andy.microservice.application1.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.andy.microservice.application1.dao.Application1Mapper;
import com.andy.microservice.application1.entity.Application1;
import com.andy.microservice.application1.service.Application1Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class Application1ServiceImpl implements Application1Service {

    @Autowired
    Application1Mapper application1Mapper;

    @Autowired
    private RedisTemplate redisTemplate;

    //    @Cacheable(value = "application1:content",key = "#root.method.name")
    @Override
    public String getContent() {
        //先从Redis中取数据
        Object result = redisTemplate.opsForValue().get("application1");
        if (null != result) {
            return result.toString();
        }
        //数据不存在或已过期，更新
        this.update();

        //再次从Redis中取数据
        Object finalResult = redisTemplate.opsForValue().get("application1");
            return finalResult.toString();
    }

    //    @CacheEvict(value = "application1:content",allEntries = true)
    public void update() {

        Application1 application1 = new Application1();
        SimpleDateFormat sdf = new SimpleDateFormat( " yyyy-MM-dd HH:mm:ss " );
        String now = sdf.format(new Date());
        application1.setContent("Application1-test to redis at" +  now);
        application1.setId(1);
        //Mybatis-plus 存储数据到mysql
        application1Mapper.updateById(application1);
        //存储数据到redis
        redisTemplate.opsForValue().set("application1", JSONUtils.toJSONString(application1.getContent()), 10, TimeUnit.SECONDS);

    }
}
